﻿using System;
using System.ComponentModel;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace VijayGande.WebParts.DocumentsViewWP
{
    [ToolboxItemAttribute(false)]
    public class DocumentsViewWP : WebPart
    {
        string documentLibraryDisplayName = string.Empty;
        string documentLibraryInternalName = string.Empty;
        string documentLibraryWebUrl = string.Empty;
        Label lblError = new Label();
        //GridView gv = new GridView();  //GridView may bot bring the sharepoint flavour to the display.
        SPGridView spGridViewDocumentLibrary = new SPGridView(); //SPGrid control bring the sharepoint flavour to the display.
        SPList list = null;
        DataView dataView = null;

        [WebBrowsable(true)]
        [WebDisplayName("Document Library Display Name")]
        [WebDescription("Enter the document library display name as it appears in the browser/UI. (e.g.Sales Resources)")]
        [Personalizable(PersonalizationScope.Shared)]
        public string DocumentLibraryDisplayName
        {
            get
            {
                return documentLibraryDisplayName;
            }
            set
            {
                documentLibraryDisplayName = value;
            }
        }

        [WebBrowsable(true)]
        [WebDisplayName("Document Library Internal Name")]
        [WebDescription("Enter the document library internal name as it appears in the url, entered while crating the documnet library. (e.g.SalesReso)")]
        [Personalizable(PersonalizationScope.Shared)]
        public string DocumentLibraryInternalName
        {
            get
            {
                return documentLibraryInternalName;
            }
            set
            {
                documentLibraryInternalName = value;
            }
        }

        [WebBrowsable(true)]
        [WebDisplayName("Document library web site name")]
        [WebDescription("Enter the web site name which contains the document library (e.g., 'http://SP2010:1000/MainWeb/SalesSubWeb')")]
        [Personalizable(PersonalizationScope.Shared)]
        public string DocumentLibraryWebURL
        {
            get
            {
                return documentLibraryWebUrl;
            }
            set
            {
                documentLibraryWebUrl = value;
            }
        }

        protected override void CreateChildControls()
        {
            //this.ChromeType = PartChromeType.None;
            try
            {
                if (ValidateInitialValues())
                {
                    if (!documentLibraryWebUrl.Equals(String.Empty))
                    {
                        using (SPSite spSiteMEDRADDP = new SPSite(documentLibraryWebUrl + "/"))
                        {
                            using (SPWeb myWeb = spSiteMEDRADDP.OpenWeb())
                            {
                                list = myWeb.Lists[documentLibraryDisplayName];
                                if (list.ItemCount > 0)
                                {
                                    dataView = list.GetItems().GetDataTable().DefaultView;
                                    BuildGrid(dataView);
                                }
                                else
                                {
                                    ShowMessage(lblError, "Document library does not contains items.");
                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        ShowMessage(lblError, "Set the custom property for document library web url.");
                        this.Controls.Add(lblError);
                        return;
                    }
                }
                else
                {
                    this.Controls.Add(lblError);
                    return;
                }
            }
            catch (Exception ex)
            {
                lblError.Text = "<b>Error occured in custom web part, Error Msg:</b> " + ex.Message + "<br/>" + "<b>Stack Trace:</b> " + ex.StackTrace;
                this.Controls.Add(lblError);
            }
        }

        private bool ValidateInitialValues()
        {
            bool bFlag = true;

            ShowMessage(lblError, "<b>Web Part Summary:</b></br>This web part displays hyperlinks to the documents of a document library, The OOTB document library view web part  can only bring the documents from the document library of the current web site, where as this web part can bring the documents from other web sites.  User has to set the document library display name, internal name and web site url in custom properties sections.</br>");

            if (documentLibraryDisplayName.Equals(String.Empty))
            {
                ShowMessage(lblError, "Set the web part custom properties for the document library display name as it appears in the browser/UI. (e.g.Sales Resources)");
                bFlag = false;
            }
            if (DocumentLibraryInternalName.Equals(String.Empty))
            {
                ShowMessage(lblError, "Set the web part custom properties for document library internal name, entered while crating the documnet library. (e.g.SalesReso), its being used to build the product specification url dynamically.");
                bFlag = false;
            }
            if (documentLibraryWebUrl.Equals(String.Empty))
            {
                ShowMessage(lblError, "Enter the web site name which contains the document library (e.g., 'http://SP2010:1000/MainWeb/SalesSubWeb')");
                bFlag = false;
            }
            return bFlag;
        }

        public void BuildGrid(DataView dataView)
        {
            spGridViewDocumentLibrary.AutoGenerateColumns = false;
            //spGridViewDocLibrary.Style = CssStyleCollection.

            HyperLinkField hlFieldDocLibItem = new HyperLinkField();
            hlFieldDocLibItem.HeaderText = "Name";
            //*LinkFilename is the Field Name Holding the Url Param
            hlFieldDocLibItem.DataNavigateUrlFields = new string[] { "LinkFilename" };
            hlFieldDocLibItem.DataNavigateUrlFormatString = documentLibraryWebUrl + "/" + documentLibraryInternalName + "/{0}";
            hlFieldDocLibItem.DataTextField = "LinkFilename";
            spGridViewDocumentLibrary.Columns.Add(hlFieldDocLibItem);

            spGridViewDocumentLibrary.DataSource = dataView;
            spGridViewDocumentLibrary.DataBind();

            //The following styles will override the SPGridView OOTB styles at runtime, these styles sets the back ground color for grid header row and
            //trys to set the height to 0px, but during the run time the sharepoint frame work / classes are pushing a &nbsp between the header td,
            //check the render out put in browser using firebug for more info.
            this.Controls.Add(new LiteralControl(
                "<style type='text/css'>"
                + ".ms-viewheadertr .ms-vh2-gridview{background-color:#FFFFFF; height:0px;text-align:left;}"
                + ".ms-viewheadertr th{background-color:#FFFFFF;height:0px;}"
                + "</style>"));

            this.Controls.Add(spGridViewDocumentLibrary);
        }

        public static void ShowMessage(Label lblCtrl, String message)
        {
            lblCtrl.Text += message + "<br/>";
        }
    }
}